﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PhotoMgr.src.database;
using popLib;
using PhotoMgr.src.common;

namespace PhotoMgr.src.gui
{
    public partial class Login : Form
    {
        public FormValidation FormValidator { get; set; }

        public string RememberLogin
        {
            get { return chx_remember.Checked ? "1" : "0"; }
            set { chx_remember.Checked = value == "1"; }
        }

        public Login()
        {
            InitializeComponent();

            this.label3.Text = Configuration.Instance.ApplicationTitle;
            this.Text = Configuration.Instance.ApplicationTitle;

            this.Icon = PhotoMgr.Properties.Resources.logo32;

            FormLib.setTransparentForm(this, 255, new TransparentFormOption() { AllowMoveForm = false });

            

            FormValidator = new FormValidation(this);
            FormValidator.ValidateText(txt_username, true, 3, -1);
            FormValidator.ValidateText(txt_password, true, 3, -1);

            RememberLogin = FormLib.getAppSettingINI("Login", "RememberLogin", "0");
            txt_username.Text = FormLib.getAppSettingINI("Login", "id", "");
            txt_password.Text = FormLib.getAppSettingINI("Login", "pw", "");
            if( StringLib.isValid(txt_password.Text) )
                txt_password.Text = StringLib.decodeFrom64(txt_password.Text, "tamduc");
        }


        private void btn_login_Click(object sender, EventArgs e)
        {
            if (FormValidator.Validate())
            {
                ReturnSet rs = DBManager.Account_Login(txt_username.Text.Trim(), txt_password.Text.Trim());
                if (rs.Success)
                {
                    User acc = (User)rs.Result;
                    Global.UpdateLoginAccount(acc);
                    DialogResult = System.Windows.Forms.DialogResult.OK;
                    this.Close();
                }
                else
                {
                    Global.FormMessage(Global.FormMessageType.LoginFail, "", null, (Global.DBErrorType)rs.Result);
                }
            }
        }

        private void btn_exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Login_FormClosing(object sender, FormClosingEventArgs e)
        {
            FormLib.setAppSettingINI("Login", "RememberLogin", RememberLogin);
            FormLib.setAppSettingINI("Login", "id", txt_username.Text);
            FormLib.setAppSettingINI("Login", "pw", chx_remember.Checked ? StringLib.encodeTo64(txt_password.Text, "tamduc") : "");
        }
    }
}
